package enterprise.manage.util;

import org.apache.poi.hssf.record.formula.functions.T;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: zhenmingyue
 * Date: 2011-7-22 11:42:11
 * Desc:
 * For :
 */
public class JdbcUtils extends JdbcDaoSupport {
    /**
     * jdbcTemplate.queryForList 查询结果转换为对象
     *
     * @param sql
     * @param object
     * @param c
     * @return
     */
    public List<T> queryForList(int pageSize, int pageNo, String sql, Object[] object, Class c) {
        sql = sqlAddRowId(sql, pageSize * (pageNo - 1), pageSize * pageNo);
        List list = new ArrayList();
        List ts = this.getJdbcTemplate().queryForList(sql, object);
        for (Object o : ts) {
            Map map = (Map) o;
            list.add(this.getBeanFromMap(map, c));
        }
        return list;
    }

    public Integer getCount(String sql, Object[] object) {
        sql = setRowCount(sql);
        return this.getJdbcTemplate().queryForInt(sql, object);
    }

    private String sqlAddRowId(String sql, int beginRow, int endRow) {
        sql = sql.toUpperCase().replaceFirst("SELECT ", "SELECT ROW_NUMBER() over(order by createTime desc) as rowNo,");
        sql = "select * from (" + sql + ") as a where a.rowNo between " + beginRow + " and " + endRow;
        return sql.toUpperCase();
    }

    public String setRowCount(String sql) {
        sql = "SELECT COUNT(1) " + sql.substring(sql.toUpperCase().indexOf("FROM"), sql.length());
        return sql.toUpperCase();
    }
    private Object getBeanFromMap(Map<String, Object> map, Class c) {
        Object object = null;
        try {
            object = c.newInstance();
            Method[] methods = c.getDeclaredMethods();
            for (Method method : methods) {
                String modifier = Modifier.toString(method.getModifiers());
                if (!modifier.contains("public")) {
                    continue;
                }

                String methodName = method.getName();
                if (!methodName.startsWith("set")) {
                    continue;
                }

                String fieldName = String.valueOf(methodName.charAt(3)).toLowerCase()
                        + methodName.substring(4);

                if (map.containsKey(fieldName)) {
                    method.invoke(object, map.get(fieldName));
                }
            }
        } catch (Exception e) {
//            System.out.println(e.getMessage());
        }
        return object;
    }
}
